/**
 * Copyright (C) 2018-2019
 * All rights reserved, Designed By www.joolun.com
 * 注意：
 * 本软件为www.joolun.com开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
const app = getApp()
import __config from '../../../config/env'

Page({
  data: {
    version: app.globalData.version,
    config: app.globalData.config,
    wxUser: null,
    userInfo: null,
    orderCountAll: []
  },
  onShow(){
    //更新tabbar购物车数量
    wx.setTabBarBadge({
      index: 2,
      text: app.globalData.shoppingCartCount + ''
    })
    
    let wxUser = app.globalData.wxUser
    this.setData({
      wxUser: wxUser
    })
    app.initPage()
      .then(res => {
        this.userInfoGet()
        this.orderCountAll()
      })
  },
  onLoad(){
    if(this.data.config.adEnable){
      // 在页面中定义插屏广告
      let interstitialAd = null
      // 在页面onLoad回调事件中创建插屏广告实例
      if (wx.createInterstitialAd) {
        interstitialAd = wx.createInterstitialAd({
          adUnitId: this.data.config.adInsertScreenID
        })
        interstitialAd.onLoad(() => { })
        interstitialAd.onError((err) => { })
        interstitialAd.onClose(() => { })
      }
      // 在适合的场景显示插屏广告
      if (interstitialAd) {
        interstitialAd.show().catch((err) => {
          console.error(err)
        })
      }
    }
  },
  /**
   * 小程序设置
  */
  settings: function () {
    wx.openSetting({
      success: function (res) {
        console.log(res.authSetting)
      }
    })
  },
  onChooseAvatar(e) {
    let that = this
    let avatarUrl  = e.detail.avatarUrl
    wx.showLoading({
      title: '加载中',
    })
    wx.uploadFile({
      url: __config.basePath + '/mall/api/ma/file/upload', 
      filePath: avatarUrl,
      header: {
        'app-id': wx.getAccountInfoSync().miniProgram.appId,
        'third-session': app.globalData.thirdSession != null ? app.globalData.thirdSession : ''
      },
      name: 'file',
      formData: {
        'fileType': 'image',
        'dir': 'userinfo/avatar/'
      },
      success (uploadFileRes){
        if(uploadFileRes.statusCode == '200'){
          let link = JSON.parse(uploadFileRes.data).link
          app.api.userInfoPut({
            id: that.data.wxUser.mallUserId,
            headimgUrl: link
          }).then(res => {
            that.userInfoGet()
        })
        }else{
          wx.showModal({
            title: '提示',
            content: '上传失败：' + uploadFileRes.data,
            success(res) {}
          });
        }
      },
      fail: (err) => {
        console.log(err)
      },
      complete(res) {
        wx.hideLoading()
      }
    })
  },
  onGetNickName(e) {
    let nickName = e.detail.value
    app.api.userInfoPut({
        id: this.data.wxUser.mallUserId,
        nickName: nickName
      }).then(res => {
      this.userInfoGet()
    })
  },
  //获取商城用户信息
  userInfoGet(){
    app.api.userInfoGet()
      .then(res => {
        this.setData({
          userInfo: res.data
        })
      })
  },
  orderCountAll(){
    app.api.orderCountAll()
      .then(res => {
        this.setData({
          orderCountAll: res.data
        })
      })
  }
})
